package com.spdzen.support;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

public class UploadFileUtils {
	public static final String TEMP_PATH = "/upload/temp";
	public static final String ADMIN_AVATAR_PATH = "/upload/admin/avatar";
	public static final String NEWS_IMAGE_PATH = "/upload/news/image";
	public static final String URL_SEPARATOR = "/";
	
	public static UploadFile saveToDirectory(MultipartFile uploadFile, HttpServletRequest request, String dirUrl) throws Exception {
		String originalFilename = uploadFile.getOriginalFilename();
		String fileExt = FilenameUtils.getExtension(originalFilename);
		String tmpPath = new StringBuilder(dirUrl).append(URL_SEPARATOR).append(UUID.randomUUID().toString()).append(".").append(fileExt).toString();
		String realPathName = request.getSession().getServletContext().getRealPath(tmpPath.toString());
		
		uploadFile.transferTo(new File(realPathName));
		
		UploadFile record = new UploadFile();
		record.setFilename(originalFilename);
		record.setExtension(fileExt);
		record.setSize(uploadFile.getSize());
		record.setUrl(tmpPath);
		
		return record;
	}
	
	public static UploadFile saveToNewsImage(MultipartFile uploadFile, HttpServletRequest request) throws Exception{
		return saveToDirectory(uploadFile, request, NEWS_IMAGE_PATH);
	}
	
	public static UploadFile saveToTemp(MultipartFile uploadFile, HttpServletRequest request) throws Exception {
		return saveToDirectory(uploadFile, request, TEMP_PATH);
	}
	
	public static String copyToDirectory(HttpServletRequest request, String url, String dirUrl) throws IOException {
		String srcpath = request.getSession().getServletContext().getRealPath(url);
		String dirpath = request.getSession().getServletContext().getRealPath(dirUrl);
		
		File src = new File(srcpath);
		if(!src.exists() || !src.isFile()){
			return "";
		}
		
		File dir = new File(dirpath);
		FileUtils.copyFileToDirectory(src, dir);
		
		return new StringBuilder(dirUrl).append(URL_SEPARATOR).append(src.getName()).toString();
	}
	
	public static String copyToAdminAvatar(HttpServletRequest request, String url) throws IOException {
		return copyToDirectory(request, url, ADMIN_AVATAR_PATH);
	}
	
	public static boolean deleteFile(HttpServletRequest request, String url) {
		String path = request.getSession().getServletContext().getRealPath(url);
		
		File file = new File(path);
		if(file.exists()){
			return FileUtils.deleteQuietly(file);
		}
		
		return false;
	}
}
